var express = require('express')
var router = express.Router()
const user = require('../utils')
const query = require('../pool')

//GET 获取热度值排行榜
router.get('/getPopularList', async (req, res) => {
  const sql = `SELECT page_from, COUNT(page_from) as popular_value, MAX(update_time) as update_time FROM see GROUP BY page_from ORDER BY COUNT(page_from) DESC`;
  const [err, data] = await query(sql)
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    res.send({
      code: 0,
      data
    })
  }
})

//GET 获取tapd列表
router.get('/getTapdList', async (req, res) => {
  const sql = `SELECT * FROM HopeTravel.tapd WHERE remove = '0'
    ORDER BY 
    CASE priority
      WHEN 'high' THEN 1
      WHEN 'medium' THEN 2
      WHEN 'low' THEN 3
      ELSE 4
    END ASC,
    update_time DESC;
  `;
  const [err, data] = await query(sql)
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    res.send({
      code: 0,
      data
    })
  }
})

// 新增tapd
router.post('/addTapd', async (req, res) => {
  const title = req.body.title ? req.body.title : '';
  const description = req.body.description ? req.body.description : '';
  const priority = req.body.priority ? req.body.priority : '';
  const assignee = req.body.assignee ? req.body.assignee : '';
  const status = req.body.status ? req.body.status : '';
  const sql = `INSERT INTO HopeTravel.tapd
(title, description, priority, assignee, status)
VALUES('${title}', '${description}', '${priority}', '${assignee}', '${status}');`
  let [err, data] = await query(sql)
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    res.send({
      code: 0,
      data: ''
    })
  }
})

// 修改tapd
router.post('/updateTapd', async (req, res) => {
  const id = req.body.id ? req.body.id : '';
  const title = req.body.title ? req.body.title : '';
  const description = req.body.description ? req.body.description : '';
  const priority = req.body.priority ? req.body.priority : '';
  const assignee = req.body.assignee ? req.body.assignee : '';
  const status = req.body.status ? req.body.status : '';
  const sql = `UPDATE HopeTravel.tapd
  SET title = '${title}', description = '${description}', priority = '${priority}',
  assignee = '${assignee}', status = '${status}' WHERE id = ${id};`
  let [err, data] = await query(sql)
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    res.send({
      code: 0,
      data: ''
    })
  }
})

// 删除tapd
router.post('/removeTapd', async (req, res) => {
  const id = req.body.id ? req.body.id : '';
  const sql = `UPDATE HopeTravel.tapd
  SET remove = '1' WHERE id = ${id};`
  let [err, data] = await query(sql)
  if (err) {
    res.send({
      code: -1,
      msg: err
    })
  } else {
    res.send({
      code: 0,
      data: ''
    })
  }
})

module.exports = router
